import  hashlib
import time
from fastapi import Depends , HTTPException , status
from fastapi.security import HTTPBearer , HTTPAuthorizationCredentials
import jwt
from jwt.exceptions import ExpiredSignatureError, DecodeError, InvalidTokenError, DecodeError, InvalidSignatureError, InvalidAudienceError, InvalidIssuerError, InvalidKeyError, InvalidAlgorithmError, MissingRequiredClaimError

from  datetime import datetime , timedelta

SECRET_KEY = "www.hhu.edu.cn/apiserver.2025"

class TAuth:
    def __init__(self):
        self.keys ={}
        self.expires = 1800

    def getToken (self , userInfo:dict):
        res = {}
        try:
            to_encode = userInfo.copy()
            expirs = datetime.utcnow()+ timedelta(seconds=self.expires)
            to_encode.update({"exp": expirs})
            res = jwt.encode(to_encode , SECRET_KEY , algorithm='HS256')
        except Exception as er:
            print(er)
        return res
    def login(self , aid , uid , sec):
        res = {
            "status":0 ,
            "userInfo":{},
            "token":{
            }
        }
        try:
            if aid in self.keys.keys():
                if uid in self.keys[aid]['users'].keys():
                    userInfo = self.keys[aid]['users'][uid]
                    pwd = userInfo['pwd']
                    secSeed = f"{aid}/{uid}/{pwd}"
                    bts = secSeed.encode('utf-8')
                    hasher = hashlib.md5()
                    hasher.update(bts)
                    md5Sec = hasher.hexdigest()
                    if md5Sec == sec :
                        res['userInfo'] = {
                            "aid": aid ,
                            "uid":uid ,
                            "nickName" : userInfo['nickName']
                        }
                        res['token']={
                            "svrtime": time.time(),
                            "expirs": self.expires,
                            "token": self.getToken(res['userInfo'])
                        }
                        res['status'] = 1
                    else:
                        res['status'] = - 9003
                else:
                    res['status'] = -9002
            else:
                res['status'] = -9001
        except Exception as er:
            print(er)
        return res
    async def verify_jwt_token(self , credentials:HTTPAuthorizationCredentials = Depends(HTTPBearer())):
        """
        验证token
        :param token:
        :param credentials: token对象
        :return: 返回用户信息
        """
        try:
            # 使用HTTPBearer依赖获取token,仅当使用第二种方法时才用
            token = credentials.credentials
            payload = jwt.decode(token, SECRET_KEY, algorithms="HS256")
            return payload

        except ExpiredSignatureError:
            raise HTTPException(
                status_code=401,
                detail={
                    'message': "Token已过期,请重新登录",
                    'data': None,
                }
            )
        except (InvalidTokenError, DecodeError, InvalidSignatureError, InvalidAudienceError,
                InvalidIssuerError, InvalidKeyError, InvalidAlgorithmError, MissingRequiredClaimError) as e:
            raise HTTPException(
                status_code=401,
                detail={
                    'message': "无效的Token",
                    'data': str(e),
                }
            )
        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail={
                    'message': "Token验证出现问题,请联系管理员",
                    'data': str(e),
                }
            )
auth = TAuth()
auth.keys ={
    "app23":{
        "appId":"app23", "appName":"业务系统" , "appDesc":"",
        "users":{
            "u11":{"userCode":"u11" , "nickName" : "应用服务" , "pwd":"123" },
            "u12":{"userCode":"u12" , "nickName" : "管理员" , "pwd":"123"},
        },
        "secs":{
            "u11":"5fed00f7610bd73120d9ae5be09587bd"
        }
    }
}

